package com.ihr360.commons.context.session;

import org.springframework.core.NamedInheritableThreadLocal;

public class Ihr360SessionContextHolder {
    private static final ThreadLocal<Ihr360SessionContext> sessionContextHolder = new NamedInheritableThreadLocal("ihr360 session context");
    private static final ThreadLocal<Ihr360SessionContext> inheritableSessionContextHolder = new NamedInheritableThreadLocal("ihr360 session context");

    private Ihr360SessionContextHolder() {
    }

    public static void resetSessionContext() {
        sessionContextHolder.remove();
        inheritableSessionContextHolder.remove();
    }

    public static void setSessionContext(Ihr360SessionContext Ihr360SessionContext) {
        setSessionContext(Ihr360SessionContext, false);
    }

    public static void setSessionContext(Ihr360SessionContext Ihr360SessionContext, boolean inheritable) {
        if (Ihr360SessionContext == null) {
            resetSessionContext();
        } else if (inheritable) {
            inheritableSessionContextHolder.set(Ihr360SessionContext);
            sessionContextHolder.remove();
        } else {
            sessionContextHolder.set(Ihr360SessionContext);
            inheritableSessionContextHolder.remove();
        }

    }

    public static Ihr360SessionContext getSessionContext() {
        Ihr360SessionContext companyContext = sessionContextHolder.get();
        if (companyContext == null) {
            companyContext = inheritableSessionContextHolder.get();
        }
        return companyContext;
    }

    public static void setSession(Ihr360Session session) {
        setSession(session, false);
    }

    public static void setSession(Ihr360Session session, boolean inheritable) {
        Object reportContext1;
        if (session != null) {
            reportContext1 = new SimpleSessionContext(session);
        } else {
            reportContext1 = null;
        }

        setSessionContext((Ihr360SessionContext) reportContext1, inheritable);
    }

    public static Ihr360Session getSession() {
        Ihr360SessionContext Ihr360SessionContext = getSessionContext();
        if (Ihr360SessionContext != null) {
            Ihr360Session Ihr360Session = Ihr360SessionContext.getSession();
            if (Ihr360Session != null) {
                return Ihr360Session;
            }
        }

        return Ihr360Session.getDefault();
    }

    public static String getCompanyId(){
        if (getSession().getUserInfo()!=null){
            return getSession().getUserInfo().getCompanyId();
        }else{
            return null;
        }
    }



}